<template>
  <j-modal :title="title"
           width="800px"
           :visible.sync="visible"
           :destroyOnClose="true"
           :okClose="false"
           @ok="handleOk">
    <a-spin :spinning="loading">
      <a-form-model v-bind="layout" ref="formModal" :model="form" :rules="rules">
        <a-form-model-item label="文件类型" prop="fileType">
          <a-radio-group :disabled="type==='edit'" v-model="form.fileType" @change="fileTypeChange">
            <a-radio value="1">文件夹</a-radio>
            <a-radio value="2">文件</a-radio>
            <!-- <a-radio value="3">视频大文件</a-radio> -->
          </a-radio-group>
        </a-form-model-item>
        <template v-if="type==='add'">
          <a-form-model-item label="文件上传" v-if="form.fileType == 3">
            <video-upload @uploaded="fileUploaded"></video-upload>
          </a-form-model-item>
          <a-form-model-item label="文件上传" v-if="form.fileType == 2" prop="fileList">
            <upload-with-media-type :disabled="type==='edit'" v-model="form.fileList"  @change="changeFileList"  :returnUrl="false"></upload-with-media-type>
          </a-form-model-item>
        </template>
        <a-form-model-item label="文件夹名称" v-if="form.fileType == 1" prop="fileName">
          <a-input v-model="form.fileName"></a-input>
        </a-form-model-item>
        <a-form-model-item label="可见范围">
          <a-select v-model="form.showRange" prop="showRange">
            <a-select-option value="1">全部可见</a-select-option>
            <a-select-option value="2">小组</a-select-option>
            <a-select-option value="3">个人可见</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="作者" prop="author">
          <a-input v-model="form.author"></a-input>
<!-- 
          <a-select v-model="form.author" labelInValue>
            <a-select-option v-for="item in authorList" :key="item.id" :value="item.id">
              {{item.name}}
            </a-select-option>
          </a-select> -->
        </a-form-model-item>
        <a-form-model-item label="作品时间" prop="contentTime">
          <j-date :showTime="true" dateFormat="YYYY-MM-DD HH:mm:ss" v-model="form.contentTime"></j-date>
        </a-form-model-item>
        <!--文件分类和所属文件夹是联动效果-->
        <a-form-model-item label="文件分类" prop="fileClassifyId">
          <a-tree-select allow-clear
                         v-model="form.fileClassifyId"
                         :placeholder="type==='edit'?'重新选择以修改，不填则不修改':'请选择文件分类'"
                         :replaceFields="{children:'crdFileBliList',key:'id',title:'fileName',value:'id'}"
                         :treeData="treeData"
                         @change="fileClassifyChange"
          ></a-tree-select>
        </a-form-model-item>
        <a-form-model-item label="所属文件夹" prop="parentId">
          <a-tree-select allow-clear
                         v-model="form.parentId"
                         :placeholder="type==='edit'?'重新选择以修改，不填则不修改':'请选择所属文件夹'"
                         :replaceFields="{children:'crdFileBliList',key:'id',title:'fileName',value:'id'}"
                         :treeData="fileTreeData"></a-tree-select>
        </a-form-model-item>
        <template v-if="form.fileType == 2 || form.fileType == 3">
          <a-form-model-item label="分组">
            <a-input-group compact v-if="customGroup">
              <a-input
                v-model="form.groupName"
                style="width:80%"
                placeholder="请输入自定义分类名称"
                maxLength="30"
              ></a-input>
              <a-button style="width: 20%" type="primary" @click="customGroup = false">选择已有分类</a-button>
            </a-input-group>
            <a-input-group compact v-else>
              <a-select style="width:80%" v-model="form.group" labelInValue>
                <a-select-option v-for="groupItem in groupList" :value="groupItem.groupName">{{
                  groupItem.groupName
                }}</a-select-option>
              </a-select>
              <a-button style="width: 20%" type="primary" @click="customGroup = true">自定义分类</a-button>
            </a-input-group>
          </a-form-model-item>
          <a-form-model-item label="标签">
            <a-select
              mode="multiple"
              style="width: 100%"
              placeholder="请选择标签"
              v-model="form.tagList"
              @focus="tagFocus"
              :disabled="type==='edit'"
            >
              <a-select-option v-for="tag in tagList" :key="tag.id" :value="tag.tagName">{{tag.tagName}}</a-select-option>
            </a-select>
          </a-form-model-item>
        </template>
      </a-form-model>
    </a-spin>
  </j-modal>
</template>

<script>
import { postAction } from '@/api/manage'
import { isAudioFile, isImgFile, isVideoFile } from '../../../utils/xinkeUtil'
import { getAction } from '../../../api/manage'
import UploadWithMediaType from '../../../components/xinke/UploadWithMediaType'
import VideoUpload from '../../../components/xinke/VideoUpload'

export default {
  name: 'AddModal',
  components: { UploadWithMediaType, VideoUpload },
  data() {
    this.layout = {
      labelCol: { md: 7, lg: 6 },
      wrapperCol: { md: 17, lg: 18 }
    };
    this.rules = {
      fileType: [{ required: true, message: '请选择文件类型' }],
      fileList: [{ required: true, message: '请上传文件并等文件上传完毕' }],
      fileName: [{ required: true, message: '请输入文件夹名称' }],
      showRange: [{ required: true, message: '请选择可见范围' }],
      author:[{required:true,message:'请选择作者'}],
      contentTime:[{required:true,message:'请选择时间'}],
      fileClassifyId:[{required:true,message:'请选择文件所属分类'}],
    };
    return {
      title: '新增',
      type:'',
      loading: false,
      visible: false,
      editId:null,
      form: {
        fileType: '1',
        fileName:'',
        fileList:null,
        contentTime:'',
        author:null,
        showRange: null,
        tagList: [],
        parentId:'',
        fileClassifyId:''
      },
      libParentList: [],
      groupList: [],
      customGroup: false,
      tagList: [],
      authorList:[],
      bigFileInfo: null,
      treeData:[],
      fileTreeData:[]
    }
  },
  methods: {
    async loadAllGroup() {
      const groupResult = await getAction('filebank/api/queryAllGroup')
      this.groupList = groupResult.result
    },
    async tagFocus(){
      if(this.form.fileClassifyId){
        const tagList = await getAction('filebank/api/queryAllTag',{parentId:this.form.fileClassifyId});
        this.tagList = tagList.result
      }
    },
    //查询作者列表
    async loadAllAuthor(){
      const authorList = await getAction('crdcontent/crdAuthor/list',{pageSize:1000});
      this.authorList = authorList.result.records;
    },
    //查询文件分类
    async queryFileClassify() {
      const params = {fileGroupType: 0};
      const res = await getAction('filebank/api/queryFileGroupAndFolder', params);
      if (res && res.success) {
        this.treeData  = res.result;
      }
    },
    //查询分类下文件夹
    async queryFileTreeData(parentId) {
      const params = {fileGroupType: 1,parentId};
      const res = await getAction('filebank/api/queryFileGroupAndFolder', params);
      if (res && res.success) {
        this.fileTreeData  = res.result;
      }
    },
    fileClassifyChange(value){
      this.form.parentId = '';
      this.queryFileTreeData(value);
    },
    //从已有标签中选择
    addTagList(tagName) {
      if (!this.form.tagList) {
        this.form.tagList = []
      }
      const item = this.form.tagList.find(item => item == tagName)
      if (!item) {
        this.form.tagList.push(tagName)
      }
    },
    show(type,params) {
      this.type = type;
      if(type === 'add'){
        this.title = '新增';
        this.rules.fileClassifyId[0].required = true;
        this.form = {
          fileType: '1',
          showRange:params.showRange,
          tagList: [],
          parentId:''
        };
      }else if(type === 'edit'){
        this.title = '编辑';
        const {fileName,parentId,authorId,authorName,contentTime,id,fileUrl} = params;
        this.editId = id;
        this.rules.fileClassifyId[0].required = false;
        this.form = {
          fileName,
          contentTime,
          author:{key:authorId,label:authorName},
          fileType: params.fileType.toString(),
          showRange:params.showRange.toString(),
          tagList: [],
        };
      }
      this.loadAllGroup();
      this.loadAllAuthor();
      this.queryFileClassify();
      this.visible = true;
    },
    fileTypeChange() {
      this.$refs.formModal.clearValidate()
    },
    addFileFormHandler(){
      if (this.form.fileList && this.form.fileList.length > 0) {
        if (!this.customGroup && this.form.group) {
          this.form.groupName = this.form.group.key
        }
      }
      this.form.sizeType = 1
      if (this.form.fileType == 3) {
        if(this.bigFileInfo == null) {
          this.$message.error('请先上传视频');
          this.loading = false;
          return false;
        }
        this.form.sizeType = 2
        this.form.guid = this.bigFileInfo.uuid
        this.form.fileName = this.bigFileInfo.filename
        this.form.fileSuffix = this.bigFileInfo.filename.split('.')[1]
      }
      const author = this.form.author;
      if(author){
        // this.form.authorId = author.key;
        // this.form.authorName = author.label.replace(/\\n/g,'').replace(/(^\s*)|(\s*$)/g,'');
        this.form.authorId = author;
        this.form.authorName = author;
      }
      this.form.parentId = this.form.parentId || this.form.fileClassifyId;
      return this.form;
    },
    editFileFormHandler(){
      const params = {
        id:this.editId,
        fileType:this.form.fileType,
        fileName:this.form.fileName,
        contentTime:this.form.contentTime,
        parentId:this.form.parentId || this.form.fileClassifyId
      };
      const author = this.form.author;
      if(author){
        params.authorId = author.key;
        params.authorName = author.label.replace(/\\n/g,'').replace(/(^\s*)|(\s*$)/g,'');
      }
      return params;
    },
    handleOk() {
      this.$refs.formModal.validate(validate => {
        if (validate) {
          this.loading = true;
          const params = this.type === 'edit'?this.editFileFormHandler():this.addFileFormHandler();
          const url = this.type === 'edit'?'filebank/api/updateFolder':'filebank/api/add';
          postAction(url, params)
            .then(res => {
              if (res.success) {
                this.visible = false;
                this.$emit('refresh')
              } else {
                this.$message.error(res.message)
              }
            })
            .finally(() => {
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    fileUploaded(e) {
      this.bigFileInfo = e
    },
    changeFileList(fileList){
       this.form.fileList = fileList
    }
  }
}
</script>

<style scoped></style>
